// pages/payment/payment.js
var app = getApp();
import { weChatPay, payDelivery } from '../../config/https';
import Toast from '../../vant/toast/toast';
import Notify from '../../vant/notify/notify';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    payway: 1, //支付方式 1=> 微信支付 2=> 货到付款
    cashPay: 0, //是否货到付款 0 ==> 否 1 ==> 是
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const data = JSON.parse(options.data)
    this.setData(Object.assign(data.order_info,{
      cashPay: data.one || 0
    }))
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  // 支付方式
  payWay(e){
    const payway = e.currentTarget.dataset.id || 1;
    this.setData({payway})
  },

  //立即支付
  payTap(){
    const type = this.data.payway
    Toast.loading({
      mask: true,
      duration: 0,
      message: '请稍后...'
    });
    if (type == 1) {
      weChatPay({
        user_id: app.globalData.user_id,
        order_number: this.data.order_number,
        total_price: this.data.realprices
      }).then( res => {
        Toast.clear()
        wx.requestPayment({
          'timeStamp': res.timeStamp,
          'nonceStr': res.nonceStr,
          'package': res.package, //
          'signType': 'MD5',
          'paySign': res.paySign,
          'success': res => {
            Toast.clear()
            Toast.success('支付成功');
            setTimeout(() => {
              wx.redirectTo({ url: '../results/results?type=1&ispay=2' })
            }, 1000)
          },
          'fail': err => {
            Toast.clear()
            Toast.fail('支付失败');
            setTimeout(() => {
              wx.redirectTo({ url: '../results/results?type=2' })
            }, 1000)
          }
        })
      })
    }
    if (type == 2){
      payDelivery({
        user_id: app.globalData.user_id,
        order_id: this.data.id
      }).then(res => {
        Toast.success('提交成功');
        setTimeout(() => {
          wx.redirectTo({ url: '../results/results?type=1&ispay=1' })
        },1000)
      }).catch(err => {
        Toast.fail('提交失败');
        setTimeout(() => {
          wx.redirectTo({ url: '../results/results?type=2' })
        }, 1000)
      })
      // Toast.success('货到付款');
    }
  },

  succNot(msg) {
    Notify({
      text: msg,
      backgroundColor: '#1989fa'
    });
  },

  failNot(msg) {
    Notify({
      text: msg,
      backgroundColor: '#f44'
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})